package com.baidu.emus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.util.TestUtil;

public class EnumRepository {
	private static EnumRepository instance = new EnumRepository();
	
	private EnumRepository(){
		TestUtil.systemOutPrintln("初始化");
		init();
	}
	
	private Map<String, List<EnumBean>> repository = new HashMap<String, List<EnumBean>>();
	
	private List<Class<?>> classes = new ArrayList<Class<?>>();
	
	private void init(){
		store(ErrorCode.class);
	}
	
	private void store(Class<?> clazz){
		try {
			classes.add(clazz);
			BaseEnum<?>[] enums = ((BaseEnum<?>[]) clazz.getMethod("values").invoke(null, null));
			String fqn = clazz.getSimpleName();
			List<EnumBean>  list  = repository.get(fqn);
			if (list == null) {
				list = new ArrayList<EnumBean>();
			}
			for(BaseEnum<?> baseEnum : enums){
				EnumBean eb = new EnumBean();
				eb.setName(baseEnum.name());
				eb.setCode(baseEnum.getCode().toString());
				eb.setDescription(baseEnum.getDescription());
				list.add(eb);
			}
			repository.put(fqn, list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static Map<String, List<EnumBean>> getRepository(){
		
		return instance.repository;
	}
	
	public static void put(String fqn, List<EnumBean> ebList){
		instance.repository.put(fqn, ebList);
	}
	
//	public static String get(String fqn, String key)
//	{
//		if(fqn == null || key == null){
//			return null;
//		}
//		Map<String, String> map = instance.repository.get(fqn);
//		if (map == null) {
//			return null;
//		}
//		return map.get(key);
//	}
	
	public static List<EnumBean> get(String fqn)
	{
		if(fqn == null){
			return null;
		}
		List<EnumBean> list = instance.repository.get(fqn);
		return list;
	}
	
	public static Class<?> getClassByFqn(String fqn){
		for(Class<?> clazz : instance.classes){
			if(clazz.getSimpleName().equals(fqn)){
				return clazz;
			}
		}
		return null;
	}
}
